package com.sky.controller.admin.user;

import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user/dish")
public class UserDishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 根据分类id查询菜品和口味
     *
     * @param categoryId
     * @return {@link Result}
     */
    @GetMapping("/list")
    public Result list(Long categoryId){
        //todo 1.构造redis中的key 规则:dish_分类id,val是个菜品集合List<DishVO> dishVOList
        String key = "dish_::"+categoryId;
        //todo 2.查询redis中是否存在key对应的菜品数据
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //todo 2.1 存在直接返回
        if (dishVOList != null && dishVOList.size() > 0){
            return Result.success(dishVOList);
        }
        //todo 2.2 不存在查询数据库,再载入缓存
        dishVOList = dishService.list(categoryId);
        redisTemplate.opsForValue().set(key,dishVOList);
        return Result.success(dishVOList);

    }
}
